package com.lnsf.bookstore.system.permission.controller;

import com.lnsf.bookstore.common.constant.Constants;
import com.lnsf.bookstore.common.constant.Constants.PermissionType;
import com.lnsf.bookstore.common.dto.ResultFailDto;
import com.lnsf.bookstore.common.dto.ResultSuccessDto;
import com.lnsf.bookstore.common.exception.RException;
import com.lnsf.bookstore.common.session.SessionProvider;
import com.lnsf.bookstore.system.permission.service.PermissionService;
import com.lnsf.bookstore.system.permission.vo.Permission;
import com.lnsf.bookstore.system.role.service.RoleService;
import com.lnsf.bookstore.system.user.vo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService ;

    @Autowired
    private SessionProvider sessionProvider;

    @Autowired
    private RoleService roleService;


    @RequestMapping("/v_list.do")
    public String list(HttpServletRequest request,ModelMap modelMap){
       return "admin/permission/permission";
    }

    /**
     * 所有菜单列表,展示
     */
    @RequestMapping("/queryAll")
    @ResponseBody
    public Object queryAll(@RequestParam Map<String, Object> params) {
        ModelMap modelMap = new ModelMap();
        Map<String, Object> map = new HashMap<String, Object>();
        System.out.println("success");
        //查询列表数据
        List<Permission> permissionList =  permissionService.listAll();
        map.put("list", permissionList);
        return map;
    }

    /**
     * 主页，用户菜单列表
     */
    @RequestMapping("/user/list.json")
    @ResponseBody
    public Object list_json(ModelMap modelMap , HttpServletRequest request) {
        System.out.println("111");
        Map<String,Object> map = new HashMap<String,Object>();
        List<Permission> list = null;
        if(sessionProvider.getUser() != null){
            Integer userId =  sessionProvider.getUser().getId(); //这里要判断一下getUse是否为空
            User user = sessionProvider.getUser();
            if(roleService.countByUserIdAndName(userId,"'" + Constants.ADMINISTRATOR+ "'")>0){
                list =  permissionService.listAllExBtn();//admin，超级管理员，列出所有
            }else {
                list = permissionService.queryPermbyUserId(userId);//列出管理员所对应的权限
            }
        }

        map.put("permissionList", list);
       return  map;
    }

    /**
     * 角色页，角色菜单列表
     */
    @RequestMapping("/role/list.json")
    @ResponseBody
    public Object list_json2(ModelMap modelMap , HttpServletRequest request) {
        Map<String,Object> map = new HashMap<String,Object>();
        List<Permission> list = null;
        Integer userId =  sessionProvider.getUser().getId();
        User user = sessionProvider.getUser();
        if(roleService.countByUserIdAndName(userId,"'" + Constants.ADMINISTRATOR+ "'")>0){  
            list =  permissionService.listAll();
        }else {
            list = permissionService.queryPermbyUserId(userId);
        }
        map.put("permissionList", list);
        return  map;
    }

    /**
     * 菜单信息
     */
    @RequestMapping("/info/{permissionId}")
    /*@RequiresPermissions("sys:menu:info")*/
    @ResponseBody
    public Object info(@PathVariable("permissionId") Integer permissionId) {
        Map<String,Object> map = new HashMap<String , Object>();
        Permission permission = permissionService.findById(permissionId);
        map.put("permission", permission);
        return  map;
    }

    /**
     * 选择菜单(添加、修改菜单)
     */
    @RequestMapping("/select")
   /* @RequiresPermissions("sys:menu:select")*/
   @ResponseBody
    public Object select() {
       Map<String,Object> map = new HashMap<String,Object>();
        //查询列表数据
        List<Permission> permissionList = permissionService.queryNotButtonList();

        //添加顶级菜单
        Permission root = new Permission();
        root.setId(0);
        root.setName("一级菜单");
        root.setParentId(-1);
        root.setOpen(true);
        permissionList.add(root);
        map.put("permissionList", permissionList);
        return map;
    }

    /**
     * 删除菜单列表
     */
    @ResponseBody
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public Object delete(HttpServletRequest request,@RequestBody Integer[] ids){
        if(ids.length==0){
            return new ResultFailDto("参数错误");
        }
        permissionService.deleteBatch(ids);

        return new ResultSuccessDto("操作成功");
    }

    /**
     * 弹出新增、修改界面,可以不用
     */
    @RequestMapping(value = "/v_saveOrUpdate", method = RequestMethod.POST)
    public String v_saveOrUpdate(HttpServletRequest request,Integer id , ModelMap modelMap){

        if(id!=0){
            Permission permission = permissionService.findById(id);
            modelMap.put("permission",permission);
        }
        return null;
    }

    /**
     * 修改、新增操作
     */
    @RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
    @ResponseBody
    public Object saveOrUpdate(HttpServletRequest request,Integer id ,@RequestBody Permission permission, ModelMap modelMap){
       if(permission.getId()==null){//新增
           verifyForm(permission);
           permissionService.save(permission);
       }else{//修改
           verifyForm(permission);
           permissionService.update(permission);
       }
        return new ResultSuccessDto("操作成功");
    }


    /**
     * 设置上级ID串
     * @param permission
     */
    private void setParentIds(Permission permission) {
        Integer pid = permission.getParentId();
        if (!"0".equals(pid)) {//有上级按钮
            Permission upPermission = permissionService.findById(pid);//上级
            if (upPermission != null) {
                StringBuilder sb = new StringBuilder();
                sb.append(upPermission.getParentIds() + ", " + upPermission.getId());
                permission.setParentIds(sb.toString());
            }
        } else {//没有上级按钮
            permission.setParentIds("0");
        }
    }

    /**
     * 验证参数是否正确
     */
    private void verifyForm(Permission permission) {
        if (StringUtils.isBlank(permission.getName())) {
            throw new RException("权限菜单名称不能为空");
        }
        if (permission.getParentId() == null) {
            throw new RException("上级菜单不能为空");
        }
        //菜单
        if (permission.getType() == PermissionType.MENU.getValue()) {
            if (StringUtils.isBlank(permission.getUrl())) {
                throw new RException("菜单URL不能为空");
            }
        }
        //上级菜单类型
        int parentType = PermissionType.CATALOG.getValue();
        if (permission.getParentId() != 0) {
            Permission parentMenu = permissionService.findById(permission.getParentId());
            parentType = parentMenu.getType();
        }
        //已经是目录、菜单
        if (permission.getType() == PermissionType.CATALOG.getValue() || permission.getType() == PermissionType.MENU.getValue()) {
            if (parentType != PermissionType.CATALOG.getValue()) {
                throw new RException("上级菜单只能为目录类型");
            }
            return;
        }
        //按钮
        if (permission.getType() == PermissionType.BUTTON.getValue()) {
            if (parentType != PermissionType.MENU.getValue()) {
                throw new RException("上级菜单只能为菜单类型");
            }
            return;
        }
    }




}
